package elephant.servers.consoleserver.termos;

import java.util.LinkedList;

/**
 * @author <a href="mailto:trygvis@java.no">Trygve Laugst&oslash;l</a>
 * @version $Id$
 */
public class ReadLineEnvironment {
    public final String encoding;
    public final Integer erase;
    public final boolean icrnl;
    public final boolean ocrnl;
    private int columns;
    private int lines;
    //
    public String user;
    public LinkedList<String> historyCommands;
    public int historyCommandIndex;//1-length
    public String prompt;
    //
    public ReadLineEnvironment(String encoding, Integer erase, boolean icrnl, 
    		boolean ocrnl, Integer columns, Integer lines,String user) {
        this.encoding = encoding;
        this.erase = erase;
        this.icrnl = icrnl;
        this.ocrnl = ocrnl;
        this.user=user;
        this.historyCommands=new LinkedList<>();
        onWindowChange(columns, lines);
    }

    public int getColumns() {
        return columns;
    }

    public int getLines() {
        return lines;
    }

    public void onWindowChange(Integer newColumns, Integer newLines) {
        this.columns = newColumns != null ? newColumns : 80;
        this.lines = newLines != null ? newLines : 25;
    }
    
    public void addHistoryCommand(String command){
    	if(historyCommands.size()>=20){
    		historyCommands.removeLast();
    	}
    	historyCommands.addFirst(command);
    	historyCommandIndex=0;
    }
    
    public String getHistoryCommandBefore(){
    	if(historyCommands.size()==0){
    		return null;
    	}
    	historyCommandIndex++;
    	if(historyCommandIndex>historyCommands.size()){
    		historyCommandIndex=historyCommands.size();
    	}
    	return historyCommands.get(historyCommandIndex-1);
    }
    
    public String getHistoryCommandAfter(){
    	if(historyCommands.size()==0){
    		return null;
    	}
    	historyCommandIndex--;
    	if(historyCommandIndex<1){
    		historyCommandIndex=1;
    	}
    	return historyCommands.get(historyCommandIndex-1);
    }
}
